package com.atao.baokede.service.serviceImpl;

import com.atao.baokede.pojo.Result;
import com.atao.baokede.service.FileService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;
    @Override
    public void deletePhoto(String url) throws Exception{
        // 截取从 "http://121.196.207.80:9000/baokede/" 之后的部分
        String fileName = url.substring(url.indexOf("http://121.196.207.80:9000/baokede/") + "http://121.196.207.80:9000/baokede/".length());
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket("baokede")
                        .object(fileName)
                        .build()
        );
    }

    @Override
    public String uploadPhoto(MultipartFile file) throws Exception{

        // 1. 获取当前日期
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        // 2. 拿到最原始的文件名
        String originalFilename = file.getOriginalFilename();

        // 3. 通过UUID构建文件名避免文件名重复
        String fileName = date + "/" + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

/*        // 4. 上传文件到OSS
        String url = AliOssUtil.uploadFile(fileName, file.getInputStream());*/

        // 4. 上传文件到Minio
        ObjectWriteResponse response = minioClient.putObject(PutObjectArgs.builder()
                .bucket("baokede")
                .object(fileName)//上传后的文件名
                .stream(file.getInputStream(),file.getSize(),-1)
                .build()
        );
        String url = "http://121.196.207.80:9000/baokede/"+fileName;
        return url;
    }
}
